'use strict';
const db = uniCloud.database()
const bsOthersPlatOrderDBName = 'zhy_business_others_plat_order'
/**
 * crud: {
				add: 1,
				del: 2,
				query: 3,
				update: 4
			},
 */
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	if (event.operateType === 1) {
		// 新增
		return await addBSOthersPlatOrder(event, context)
	}
	//返回数据给客户端
	return event
};

async function addBSOthersPlatOrder(event, context) {
	let result = {
		code: 0, //1成功 0失败
		msg: '' //错误信息
	}
	if (objIsEmpty(event.business_id) || objIsEmpty(event.order_id) || objIsEmpty(event.plat_no) ||
		objIsEmpty(event.order_amount)) {
		result.msg = '参数错误'
		return result
	}
	let addParam = {
		business_id: event.business_id,
		plat_no: event.plat_no,
		order_id: event.order_id,
		order_amount: event.order_amount,
		used: 0,
		create_time: new Date().getTime()
	}
	// 判断是否存在
	let exist = await othersPlatOrderIsExist(event.order_id)
	if (exist) {
		result.msg = '此订单号已存在，请勿重复录入'
		return result
	}
	await db.collection(bsOthersPlatOrderDBName).add(addParam)
	result.code = 1
	return result
}

// 判断用户三方平台订单号是否存在
async function othersPlatOrderIsExist(order_id) {
	let res = await db.collection(bsOthersPlatOrderDBName).where({
		order_id: order_id
	}).get()
	if (res == null || res.data == null || res.data.length == 0) {
		return false
	}
	return true
}

function objIsEmpty(obj) {
	if (obj == undefined || obj == '' || obj == null || JSON.stringify(obj) == '{}') {
		return true
	}
	return false
}